import time
import re
from random import randint
from urllib.request import urlopen
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

Option = Options()
# Option.add_argument('--headless')  # 不额外将浏览器显示出来，界面整洁一点
timestamp_start = 0
timestamp_lenth = 0


def process_ip(cur_ip):
    pattern_nums = re.compile(r'\d+')
    ip_nums = re.findall(pattern_nums, cur_ip)
    ip_No3 = int(ip_nums[2])
    ip_No4 = int(ip_nums[3])
    if 3 < ip_No4 < 255:
        ip_No4 += 1
        if ip_No3 != 94 and ip_No3!=95:
            ip_No3 = 94
    elif ip_No4 == 255:
        ip_No4 = 4
        if ip_No3 == 94:
            ip_No3 = 95
        else:
            ip_No3 = 94
    ip_nums[2] = str(ip_No3)
    ip_nums[3] = str(ip_No4)
    ret = ip_nums[0]
    for i in range(1, 4):
        ret += '.' + ip_nums[i]
    return ret


def Internet_on(test_pool):
    try:
        response = urlopen(test_pool[randint(0, 5)], timeout=10)
        return True
    except:
        return False


def Current_time():
    return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))


test_pool = ['https://mail.163.com/', 'https://www.baidu.com', 'https://www.sogou.com', 'https://www.sohu.com/',
             'https://www.sohu.com/', 'https://zhuanlan.zhihu.com/']
if __name__ == '__main__':
    init = 0
    just_logged = 0
    relogging = 0
    already_on = 0
    while True:

        if Internet_on(test_pool):
            if not init:
                print("Initialized with Internet_On：" + Current_time())
                already_on = 1
                if not timestamp_start:
                    timestamp_start = time.time()
                init = 1
            elif just_logged:
                print("Gateway logged success:" + Current_time())
                just_logged = 0
            elif not already_on:
                print("Internet on,Checked at：" + Current_time())
                already_on = 1
                if not timestamp_start:
                    timestamp_start = time.time()
            time.sleep(5)  # sleep for 5seconds
            try:
                driver.quit()
            except:
                pass

        else:
            driver = webdriver.Chrome(options=Option)
            if not relogging and not init:
                print("Initialized with Internet off: " + Current_time())
                init = 1
            elif not relogging:
                print("Internet off: " + Current_time())
            if already_on:
                already_on = 0
                timestamp_lenth = (time.time() - timestamp_start) / 3600
                print("Last Total Online Time：%.3fh" % timestamp_lenth)
                timestamp_start = 0
                if timestamp_lenth <= 1:  # 如果上次网络连接持续不满1小时
                    try:
                        driver.get('http://192.168.3.1/html/index.html#/login')  # 登路由器管理页面
                        time.sleep(2)
                        driver.find_element(By.ID, "userpassword_ctrl").send_keys("buaae401")
                        driver.find_element(By.ID, "loginbtn").click()
                        time.sleep(2)
                        driver.find_element(By.ID, "internet").click()
                        time.sleep(2)
                        iptext = driver.find_element(By.ID, "wan_internet_ipaddress_ctrl")
                        cur_ip = iptext.get_attribute('value')
                        iptext.clear()
                        iptext.send_keys(process_ip(cur_ip))
                        driver.find_element(By.ID, "wan_submit_item_submitbutton").click()
                        time.sleep(20)


                    except:
                        print('!!!Warning: Host connection lost!!! at:' + Current_time())
                    driver.quit()

            driver = webdriver.Chrome(options=Option)
            try:
                driver.get('https://gw.buaa.edu.cn/srun_portal_pc?ac_id=1&theme=buaa')  # 无法连接网络时尝试找gw
            except:  # 无法访问gw
                driver.quit()
                print("!!!Warning: Gateway cannot be reached at: " + Current_time())
                print("Retrying to reach Gateway in 20s")
                relogging = 1
                time.sleep(20)
            else:  # 无法连接网络但能访问gw
                try:
                    time.sleep(2)
                    driver.find_element(By.ID, 'login')  # 找到gw 看看能否login
                except:  # 没找到login，说明已经登陆完毕
                    driver.quit()
                    print("Already logged into Gateway " + Current_time())
                else:
                    # gateway找到了login,未登录，发送信息登录
                    print("Gateway reached, but not logged in yet: " + Current_time())
                    print("Trying to log into Gateway")
                    driver.find_element(By.ID, "username").send_keys('sy2203117')
                    driver.find_element(By.ID, "password").send_keys('!Cool52334488')
                    driver.find_element(By.ID, "login").click()
                    time.sleep(1)
                    driver.quit()
                    just_logged = 1
                    relogging = 0
